﻿using DataManageSystem.Common;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Services;
using DataManageSystem.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class NoticeController : ControllerBase
    {
        private readonly NoticeServices noticeServices;
        private readonly UserServices userService;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IConfiguration _config;

        public NoticeController(
            NoticeServices noticeServices, 
            UserServices userService,
            IHttpContextAccessor httpContextAccessor,
            IConfiguration config
        )
        {
            this.noticeServices = noticeServices;
            this.userService = userService;
            this.httpContextAccessor = httpContextAccessor;
            this._config = config;
        }

        [HttpGet("selectNoticeData")]
        public ObjectResult selectNoticeData(
            [FromQuery] int pageNum = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string title = ""
        )
        {
            var res = noticeServices.selectNoticeData(pageNum,pageSize,title);
            return new ObjectResult(Result.Success(res));
        }

        [HttpPost("add")]
        public ObjectResult addNotice([FromBody] Notice notice)
        {
            User currentUser = TokenUtils.GetCurrentUser(httpContextAccessor, userService, _config);
            var user = userService.getUserById(currentUser.Id);
            notice.UserName = user.Username;
            notice.Time = DateTime.Now.ToString();
            notice.Open = true;
            noticeServices.add(notice);
            return new ObjectResult(Result.Success("添加成功"));
        }

        [HttpDelete("delete/{id}")]
        public ObjectResult Delete(int id)
        {
            try
            {
                noticeServices.Delete(id);
                return new ObjectResult(Result.Success("删除成功"));
            }
            catch (ServiceException ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
        }
    }
}
